<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once('phpass-0.3/PasswordHash.php');

define('PHPASS_HASH_STRENGTH', 8);
define('PHPASS_HASH_PORTABLE', false);

/**
 * SimpleLoginSecure Class
 *
 * Makes authentication simple and secure.
 *
 * Simplelogin expects the following database setup. If you are not using 
 * this setup you may need to do some tweaking.
 *   
 * 
 *   CREATE TABLE `users` (
 *     `admin_id` int(10) unsigned NOT NULL auto_increment,
 *     `admin_email` varchar(255) NOT NULL default '',
 *     `admin_pass` varchar(60) NOT NULL default '',
 *     `admin_date` datetime NOT NULL default '0000-00-00 00:00:00' COMMENT 'Creation date',
 *     `admin_modified` datetime NOT NULL default '0000-00-00 00:00:00',
 *     `admin_last_login` datetime NULL default NULL,
 *     PRIMARY KEY  (`admin_id`),
 *     UNIQUE KEY `admin_email` (`admin_email`),
 *   ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 * 
 * @package   SimpleLoginSecure
 * @version   2.1.1
 * @author    Stéphane Bourzeix, Pixelmio <stephane[at]bourzeix.com>
 * @copyright Copyright (c) 2012-2013, Stéphane Bourzeix
 * @license   http://www.gnu.org/licenses/gpl-3.0.txt
 * @link      https://github.com/DaBourz/SimpleLoginSecure
 */
class SimpleLoginSecure
{
	var $CI;
	var $admin_table = 'administrators';

	/**
	 * Create a user account
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @param	bool
	 * @return	bool
	 */
	function create($admin_email = '', $admin_pass = '', $auto_login = true) 
	{
		$this->CI =& get_instance();

        //Make sure account info was sent
		if($admin_email == '' OR $admin_pass == '') {
			return false;
		}
		
		//Check against user table
		$this->CI->db->where('admin_email', $admin_email); 
		$query = $this->CI->db->get_where($this->admin_table);
		
		if ($query->num_rows() > 0) //admin_email already exists
			return false;

		//Hash admin_pass using phpass
		$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);
		$admin_pass_hashed = $hasher->HashPassword($admin_pass);

		//Insert account into the database
		$data = array(
					'admin_email' => $admin_email,
					'admin_pass' => $admin_pass_hashed,
					'admin_date' => date('c'),
					'admin_modified' => date('c'),
				);

		$this->CI->db->set($data); 

		if(!$this->CI->db->insert($this->admin_table)) //There was a problem! 
			return false;						
				
		if($auto_login)
			$this->login($admin_email, $admin_pass);
		
		return true;
	}

	/**
	 * Update a user account
	 *
	 * Only updates the email, just here for you can 
	 * extend / use it in your own class.
	 *
	 * @access	public
	 * @param integer
	 * @param	string
	 * @param	bool
	 * @return	bool
	 */
	function update($admin_id = null, $admin_email = '', $auto_login = true) 
	{
		$this->CI =& get_instance();

		//Make sure account info was sent
		if($admin_id == null OR $admin_email == '') {
			return false;
		}
		
		//Check against user table
		$this->CI->db->where('admin_id', $admin_id);
		$query = $this->CI->db->get_where($this->admin_table);
		
		if ($query->num_rows() == 0){ // user don't exists
			return false;
		}
		
		//Update account into the database
		$data = array(
					'admin_email' => $admin_email,
					'admin_modified' => date('c'),
				);
 
		$this->CI->db->where('admin_id', $admin_id);

		if(!$this->CI->db->update($this->admin_table, $data)) //There was a problem! 
			return false;						
				
		if($auto_login){
			$admin_data['admin_email'] = $admin_email;
			$admin_data['user'] = $admin_data['admin_email']; // for compatibility with Simplelogin
			
			$this->CI->session->set_userdata($admin_data);
			}
		return true;
	}

	/**
	 * Login and sets session variables
	 *
	 * @access	public
	 * @param	string
	 * @param	string
	 * @return	bool
	 */
	function login($admin_email = '', $admin_pass = '') 
	{
		$this->CI =& get_instance();

		if($admin_email == '' OR $admin_pass == '')
			return false;


		//Check if already logged in
		if($this->CI->session->userdata('admin_email') == $admin_email)
			return true;
		
		
		//Check against user table
		$this->CI->db->where('admin_email', $admin_email); 
		$query = $this->CI->db->get_where($this->admin_table);

		
		if ($query->num_rows() > 0) 
		{
			$admin_data = $query->row_array(); 

			$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);

			if(!$hasher->CheckPassword($admin_pass, $admin_data['admin_pass']))
				return false;

			//Destroy old session
			$this->CI->session->sess_destroy();
			
			//Create a fresh, brand new session
			$this->CI->session->sess_create();

//			$this->CI->db->simple_query('UPDATE ' . $this->admin_table  . ' SET admin_last_login = NOW() WHERE admin_id = ' . $admin_data['admin_id']);

			//Set session data
			unset($admin_data['admin_pass']);
			$admin_data['user'] = $admin_data['admin_email']; // for compatibility with Simplelogin
			$admin_data['logged_in'] = true;
			$this->CI->session->set_userdata($admin_data);
			
			return true;
		} 
		else 
		{
			return false;
		}	

	}

	/**
	 * Logout user
	 *
	 * @access	public
	 * @return	void
	 */
	function logout() {
		$this->CI =& get_instance();		

		$this->CI->session->sess_destroy();
	}

	/**
	 * Delete user
	 *
	 * @access	public
	 * @param integer
	 * @return	bool
	 */
	function delete($admin_id) 
	{
		$this->CI =& get_instance();
		
		if(!is_numeric($admin_id))
			return false;			

		return $this->CI->db->physical_delete($this->admin_table, array('admin_id' => $admin_id));
	}
	
	
	/**
	* Edit a user password
	* @author    Stéphane Bourzeix, Pixelmio <stephane[at]bourzeix.com>
	* @author    Diego Castro <castroc.diego[at]gmail.com>
	*
	* @access  public
	* @param  string
	* @param  string
	* @param  string
	* @return  bool
	*/
	function edit_password($admin_email = '', $old_pass = '', $new_pass = '')
	{
		$this->CI =& get_instance();
		// Check if the password is the same as the old one
		$this->CI->db->select('admin_pass');
		$query = $this->CI->db->get_where($this->admin_table, array('admin_email' => $admin_email));
		$admin_data = $query->row_array();

		$hasher = new PasswordHash(PHPASS_HASH_STRENGTH, PHPASS_HASH_PORTABLE);	
		if (!$hasher->CheckPassword($old_pass, $admin_data['admin_pass'])){ //old_pass is the same
			return FALSE;
		}
		
		// Hash new_pass using phpass
		$admin_pass_hashed = $hasher->HashPassword($new_pass);
		// Insert new password into the database
		$data = array(
			'admin_pass' => $admin_pass_hashed,
			'admin_modified' => date('c')
		);
		
		$this->CI->db->set($data);
		$this->CI->db->where('admin_email', $admin_email);
		if(!$this->CI->db->update($this->admin_table, $data)){ // There was a problem!
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
        /**
	* Show list admin account
	* @author    Stéphane Bourzeix, Pixelmio <stephane[at]bourzeix.com>
	* @author    Diego Castro <castroc.diego[at]gmail.com>
	*
	* @access  public
	* @param  string
	* @param  string
	* @param  string
	* @return  bool
	*/
	function show_list()
	{
		$this->CI =& get_instance();
		// Check if the password is the same as the old one
		$this->CI->db->select('admin_id');
		$this->CI->db->select('admin_email');
		$admin_data = $this->CI->db->get_list($this->admin_table);
                return $admin_data;
	}
	
}
?>
